// edit.js
// 用例集编辑页逻辑

// API配置
const API_BASE_URL = 'http://localhost:8000';

const columns = [
  { id: 'module', name: '功能模块' },
  { id: 'casenum', name: '用例编号' },
  { id: 'scene', name: '测试场景' },
  { id: 'pre', name: '前置条件' },
  { id: 'steps', name: '测试步骤' },
  { id: 'expect', name: '预期结果' },
];

let caseData = [];
let msgId = '';
let suiteId = ''; // 测试用例集编号
let modifiedRows = new Set(); // 记录已修改的行

function getMsgId() {
  const url = new URL(window.location.href);
  return url.searchParams.get('msgId') || '';
}

function getTableData() {
  // 优先从 localStorage 取
  const local = localStorage.getItem('editTableData');
  if (local) {
    localStorage.removeItem('editTableData');
    try {
      return JSON.parse(local);
    } catch (e) {
      return [];
    }
  }
  // 兼容老的 url 传参
  const url = new URL(window.location.href);
  const dataParam = url.searchParams.get('data');
  if (dataParam) {
    try {
      return JSON.parse(decodeURIComponent(dataParam));
    } catch (error) {
      return [];
    }
  }
  return [];
}

function getChatId() {
  const url = new URL(window.location.href);
  return url.searchParams.get('chatId') || '';
}

function getSuiteId() {
  const url = new URL(window.location.href);
  return url.searchParams.get('suite_id') || '';
}

// API调用函数
// 查询测试用例
async function getTestCases(suiteId) {
  try {
    const response = await fetch(`${API_BASE_URL}/v1/testcase/getTestCase?suiteId=${suiteId}`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
      }
    });
    
    const data = await response.json();
    
    if (data.code === 10000) {
      return data.data.testCases || [];
    } else {
      throw new Error(data.msg || '获取测试用例失败');
    }
  } catch (error) {
    console.error('获取测试用例失败:', error);
    throw error;
  }
}

// 更新测试用例
async function updateTestCase(caseId, detail) {
  try {
    const response = await fetch(`${API_BASE_URL}/v1/testcase/updateTestCase`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        caseId: caseId,
        detail: detail
      })
    });
    
    const data = await response.json();
    
    if (data.code === 10000) {
      return true;
    } else {
      throw new Error(data.msg || '更新测试用例失败');
    }
  } catch (error) {
    console.error('更新测试用例失败:', error);
    throw error;
  }
}

// 删除测试用例
async function deleteTestCase(caseId) {
  try {
    const response = await fetch(`${API_BASE_URL}/v1/testcase/deleteTestCase?caseId=${caseId}`, {
      method: 'DELETE',
      headers: {
        'Content-Type': 'application/json',
      }
    });
    
    const data = await response.json();
    
    if (data.code === 10000) {
      return true;
    } else {
      throw new Error(data.msg || '删除测试用例失败');
    }
  } catch (error) {
    console.error('删除测试用例失败:', error);
    throw error;
  }
}

// 新增测试用例API
async function addTestCase(suiteId, detail) {
  const response = await fetch(`${API_BASE_URL}/v1/testcase/addTestCase`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ suiteId, testcasedetail: detail })
  });
  const data = await response.json();
  if (data.code === 10000) {
    return true;
  } else {
    throw new Error(data.msg || '新增测试用例失败');
  }
}

function renderTable(data) {
  const tbody = document.getElementById('tableBody');
  tbody.innerHTML = '';
  
  data.forEach((row, index) => {
    const tr = document.createElement('tr');
    tr.dataset.index = index;
    
    // 添加数据列
    columns.forEach(col => {
      const td = document.createElement('td');
      const textarea = document.createElement('textarea');
      textarea.value = row[col.id] || '';
      textarea.placeholder = `输入${col.name}`;
      textarea.addEventListener('input', async (e) => {
        caseData[index][col.id] = e.target.value;
        // 自动调整高度
        e.target.style.height = 'auto';
        e.target.style.height = Math.min(e.target.scrollHeight, 200) + 'px';
        // 立即调接口保存
        const testCase = caseData[index];
        if (testCase.case_id) {
          // 构造 detail
          const detail = {
            feature: testCase.module || '',
            casenum: testCase.casenum || '',
            scenario: testCase.scene || '',
            preconditions: testCase.pre || '',
            steps: testCase.steps || '',
            expected: testCase.expect || ''
          };
          try {
            await updateTestCase(testCase.case_id, detail);
            e.target.style.background = '#e6ffe6'; // 成功绿色高亮
            setTimeout(() => { e.target.style.background = ''; }, 800);
          } catch (err) {
            e.target.style.background = '#ffe6e6'; // 失败红色高亮
            setTimeout(() => { e.target.style.background = ''; }, 1200);
            alert('保存失败: ' + (err && err.message ? err.message : err));
          }
        }
      });
      // 初始化高度
      textarea.style.height = 'auto';
      textarea.style.height = Math.min(textarea.scrollHeight, 200) + 'px';
      td.appendChild(textarea);
      tr.appendChild(td);
    });
    
    // 添加删除按钮列
    const td = document.createElement('td');
    const deleteBtn = document.createElement('button');
    deleteBtn.className = 'delete-btn';
    deleteBtn.textContent = '删除';
    deleteBtn.onclick = () => deleteRow(index);
    td.appendChild(deleteBtn);
    tr.appendChild(td);
    
    tbody.appendChild(tr);
  });
}

// 标记行已修改
function markRowAsModified(index) {
  modifiedRows.add(index);
  updateSaveButtonState();
}

// 更新保存按钮状态
function updateSaveButtonState() {
  const saveBtn = document.getElementById('saveBtn');
  if (saveBtn) {
    saveBtn.disabled = modifiedRows.size === 0;
    saveBtn.textContent = modifiedRows.size > 0 ? `保存 (${modifiedRows.size}项)` : '保存';
  }
}

// 保存所有修改的测试用例到后端
async function saveAllModifiedTestCases() {
  if (modifiedRows.size === 0) {
    alert('没有需要保存的修改');
    return;
  }
  
  const saveBtn = document.getElementById('saveBtn');
  if (saveBtn) {
    saveBtn.disabled = true;
    saveBtn.textContent = '保存中...';
  }
  
  let successCount = 0;
  let errorCount = 0;
  const errors = [];
  
  for (const index of modifiedRows) {
    const testCase = caseData[index];
    if (!testCase || !testCase.case_id) {
      errors.push(`第${index + 1}行: 用例编号不能为空！`);
      errorCount++;
      continue;
    }
    // 校验所有 detail 字段
    const fields = [
      { key: 'module', name: '功能模块' },
      { key: 'casenum', name: '用例编号' },
      { key: 'scene', name: '测试场景' },
      { key: 'pre', name: '前置条件' },
      { key: 'steps', name: '测试步骤' },
      { key: 'expect', name: '预期结果' }
    ];
    let hasEmpty = false;
    for (const f of fields) {
      if (!testCase[f.key] || String(testCase[f.key]).trim() === '') {
        errors.push(`第${index + 1}行: 【${f.name}】不能为空！`);
        errorCount++;
        hasEmpty = true;
        break;
      }
    }
    if (hasEmpty) continue;
    try {
      const detail = {
        feature: String(testCase.module || '').trim(),
        scenario: String(testCase.scene || '').trim(),
        preconditions: String(testCase.pre || '').trim(),
        steps: String(testCase.steps || '').trim(),
        expected: String(testCase.expect || '').trim()
      };
      await updateTestCase(testCase.case_id, detail);
      console.log(`测试用例 ${testCase.case_id} 保存成功`);
      successCount++;
    } catch (error) {
      console.error(`保存测试用例 ${testCase.case_id} 失败:`, error);
      errorCount++;
      errors.push(`第${index + 1}行: ${error.message}`);
    }
  }
  
  // 清空修改标记
  modifiedRows.clear();
  updateSaveButtonState();
  
  // 显示保存结果
  if (errorCount === 0) {
    alert(`保存成功！共保存了 ${successCount} 项修改。`);
  } else {
    alert(`保存完成！成功 ${successCount} 项，失败 ${errorCount} 项。\n\n失败详情：\n${errors.join('\n')}`);
  }
}

// 删除测试用例（从后端和前端）
async function deleteRow(index) {
  const testCase = caseData[index];
  if (!testCase) return;
  
  if (confirm('确定要删除这一行吗？')) {
    try {
      // 如果有caseId，先删除后端数据
      const deleteId = testCase.case_id;
      if (deleteId) {
        await deleteTestCase(deleteId);
        console.log(`测试用例 ${deleteId} 删除成功`);
      }
      
      // 从前端数据中删除
      caseData.splice(index, 1);
      renderTable(caseData);
    } catch (error) {
      console.error(`删除测试用例失败:`, error);
      alert(`删除失败: ${error.message}`);
    }
  }
}

async function addRow() {
  const row = {};
  columns.forEach(col => {
    row[col.id] = '';
  });
  caseData.push(row);
  renderTable(caseData);
  
  // 如果有suiteId，可以在这里调用后端API创建新的测试用例
  // 注意：这里需要根据实际的后端API设计来实现
  // 目前接口文档中没有创建测试用例的接口，所以暂时只在前端添加
  console.log('新测试用例已添加到前端，等待用户填写内容后自动保存');
}

async function fetchData() {
  msgId = getMsgId();
  suiteId = getSuiteId(); // 获取suiteId
  
  // 优先使用URL传递的表格数据
  const urlData = getTableData();
  if (urlData && urlData.length > 0) {
    // 转换数据格式以匹配编辑页面的字段名
    caseData = urlData.map(row => ({
      module: row.feature || '',
      casenum: row.casenum || '', // 用于后端操作
      scene: row.scenario || '',
      pre: row.preconditions || '',
      steps: row.steps || '',
      expect: row.expected || '',
      case_id: row.case_id || row.caseId || row.id || '', // 添加 case_id 字段
      suiteId: row.suite_id || row.suiteId || ''
    }));
    renderTable(caseData);
    return;
  }

  // 如果有suiteId，从后端API获取数据
  if (suiteId) {
    try {
      const testCases = await getTestCases(suiteId);
      // 转换数据格式以匹配编辑页面的字段名
      caseData = testCases.map(row => ({
        module: row.feature || '',
        casenum : row.casenum || '',
        scene: row.scenario || '',
        pre: row.preconditions || '',
        steps: row.steps || '',
        expect: row.expected || '',
        case_id: row.case_id || row.caseId || row.id || ''
      }));
      renderTable(caseData);
      return;
    } catch (error) {
      console.error('从后端获取测试用例失败:', error);
      // 如果后端获取失败，尝试从本地API获取
    }
  }
  
  // 如果没有suiteId或后端获取失败，尝试从本地API获取
  try {
    const response = await fetch(`/api/cases?msgId=${encodeURIComponent(msgId)}`);
    const res = await response.json();
    caseData = Array.isArray(res.data) ? res.data : [];
    renderTable(caseData);
  } catch (error) {
    console.error('获取测试用例数据失败:', error);
    caseData = [];
    renderTable(caseData);
  }
}

function exportTable(type) {
  if (!caseData.length) return alert('无数据可导出');
  if (type === 'csv') {
    const header = columns.map(c => c.name).join(',');
    const rows = caseData.map(row => 
      columns.map(c => '"' + (row[c.id] || '').replace(/"/g, '""') + '"').join(',')
    );
    const csv = [header, ...rows].join('\r\n');
    const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
    saveAs(blob, 'cases.csv');
  } 
  else if (type === 'markdown') {
    let md = '| ' + columns.map(c => c.name).join(' | ') + ' |\n';
    md += '| ' + columns.map(() => '---').join(' | ') + ' |\n';
    caseData.forEach(row => {
      md += '| ' + columns.map(c => (row[c.id] || '').replace(/\|/g, '\\|')).join(' | ') + ' |\n';
    });
    const blob = new Blob([md], { type: 'text/markdown' });
    saveAs(blob, 'cases.md');
  } 
  else if (type === 'excel') {
    try {
      const workbook = XLSX.utils.book_new();
      // 只导出六列，不导出 case_id 和 suiteId
      const exportData = caseData.map(row => ({
        '功能模块': row.module,
        '用例编号': row.casenum,
        '测试场景': row.scene,
        '前置条件': row.pre,
        '测试步骤': row.steps,
        '预期结果': row.expect
      }));
      const worksheet = XLSX.utils.json_to_sheet(exportData);
      XLSX.utils.book_append_sheet(workbook, worksheet, '用例集');
      const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
      const blob = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
      saveAs(blob, 'cases.xlsx');
    } catch (error) {
      console.error('Excel导出失败:', error);
      alert('Excel导出失败，请尝试其他格式');
    }
  }
  else if (type === 'word') {
    downloadWord(caseData);
  }
}

function downloadWord(data) {
  const headers = ['功能模块', '用例编号', '测试场景', '前置条件', '测试步骤', '预期结果'];
  let html = '<html><head><meta charset="utf-8"></head><body>';
  html += `<h2>测试用例导出</h2>`;
  html += '<table border="1" cellpadding="5" cellspacing="0" style="border-collapse:collapse;">';
  html += '<tr>' + headers.map(h => `<th>${h}</th>`).join('') + '</tr>';
  data.forEach(row => {
    html += '<tr>' + [row.module, row.casenum, row.scene, row.pre, row.steps, row.expect].map(cell => `<td>${cell || ''}</td>`).join('') + '</tr>';
  });
  html += '</table></body></html>';
  const blob = new Blob(['\ufeff' + html], { type: 'application/msword' });
  const link = document.createElement('a');
  link.href = URL.createObjectURL(blob);
  link.download = `测试用例_${new Date().toISOString().slice(0, 10)}.doc`;
  link.click();
  alert('Word文档下载成功');
}

document.addEventListener('DOMContentLoaded', () => {
  fetchData();
  
  // 初始化保存按钮状态
  updateSaveButtonState();
  
  // 返回按钮
  document.getElementById('backBtn').onclick = () => {
    const chatId = getChatId();
    if (chatId) {
      // 返回到对应的对话
      window.location.href = `index.html?chatId=${chatId}`;
    } else {
      // 如果没有对话ID，返回主页
      window.location.href = 'index.html';
    }
  };
  
  // 新增按钮
  const addBtn = document.getElementById('addBtn');
  if (addBtn) {
    addBtn.onclick = function() {
      document.getElementById('addCaseModal').style.display = 'flex';
    };
  }
  document.getElementById('closeAddCaseModal').onclick = function() {
    document.getElementById('addCaseModal').style.display = 'none';
  };

 // 表单提交
  const addCaseForm = document.getElementById('addCaseForm');
  addCaseForm.onsubmit = async function(e) {
    e.preventDefault();
    const form = e.target;
    const detail = {
      feature: form.module.value.trim(),
      casenum: form.casenum.value.trim(),
      scenario: form.scene.value.trim(),
      preconditions: form.pre.value.trim(),
      steps: form.steps.value.trim(),
      expected: form.expect.value.trim()
    };
    // 校验
    for (let key in detail) {
      if (!detail[key]) {
        alert('请填写所有字段');
        return;
      }
    }
    // 优先从 caseData 第一行 suiteId 或 suite_id 字段获取
    let suite_id = '';
    if (caseData.length > 0) {
      suite_id = caseData[0].suiteId || caseData[0].suite_id || '';
    }
    if (!suite_id) suite_id = suiteId;
    try {
      await addTestCase(suite_id, detail);
      // 新增成功，追加到caseData并刷新表格
      caseData.push({
        module: detail.feature,
        casenum: detail.casenum,
        scene: detail.scenario,
        pre: detail.preconditions,
        steps: detail.steps,
        expect: detail.expected,
        case_id: '', // 如果后端返回了id可补充
        suiteId: suite_id // 保持和 caseData 字段一致
      });
      renderTable(caseData);
      document.getElementById('addCaseModal').style.display = 'none';
      form.reset();
      alert('新增成功');
    } catch (err) {
      alert('新增失败: ' + err.message);
    }
  };

  // 保存按钮
  // document.getElementById('saveBtn').onclick = saveAllModifiedTestCases;

  // 下载按钮
  document.getElementById('downloadBtn').onclick = () => {
    const type = document.getElementById('exportType').value;
    exportTable(type);
  };
});